<?php

// Namespace

namespace Snsfg;


// Dependencies

require_once(PATH_APPLICATION . 'Class/ISocialNetworkDriver.php');

require_once(PATH_APPLICATION . 'Component/Renren/RennClient.php');

require_once(PATH_APPLICATION . 'Model/CAccount.php');
require_once(PATH_APPLICATION . 'Model/CPostStatus.php');


/**
 * CRenrenDriver allows to run and use the social network driver for PHP
 * This class is the implementation of the interface ISocialNetworkDriver
 *
 * @package		Snsfg
 * @category	Driver
 */

class CRenrenDriver implements ISocialNetworkDriver
{
	
	/**
	 *
	 */

	public function completeConnection(&$account)
	{
		$code = fv('code', true);
		
		$renrenOauthApi = new \RenrenOAuthApiService();

		$get_access_token_params = array
		(
			'client_id' => pref('[Snsfg]/socialNetwork/renren/apikey'),
			'client_secret' => pref('[Snsfg]/socialNetwork/renren/secretkey'),
			'redirect_uri' => url
			(
				'api/json/Account.completeConnection', 
				array
				(
					'accountId' => $account->getId(), 
					'accountReference' => $account->getReference(),
					'urlOfRedirection' => fv('urlOfRedirection')
				)
			),

			'grant_type' => 'authorization_code',
			'code'=>$code
		);
			
		$oauthInfo = $renrenOauthApi->rr_post_curl
		(
			pref('[Snsfg]/socialNetwork/renren/tokenurl'), 
			$get_access_token_params
		);


		$rennClient = $this->connectDriver
							(
									array
									(
										'privateApiToken' => $account->getPrivateApiToken()
									)
								);

		$params = array
		(
			'access_token' => $oauthInfo['access_token'],
			'uid' => $oauthInfo['user']['id'],
			'fields' => 'base_info,status,visitors_count,blogs_count,friends_count,guestbook_count,status_count'
		);

		$accountInfo = $renrenRestApi->rr_post_curl('users.getProfileInfo', $params);

		// Try to get the social network account

		$account->loadAccount('internalId', $accountInfo['uid'], SOCIAL_NETWORK_RENREN);
		
		$account->setPrivateApiToken($oauthInfo['access_token']);
		$account->setRefreshToken($oauthInfo['refresh_token']);
		$account->setInternalId($accountInfo['uid']);
		$account->setScreenName($accountInfo['name']);
		$account->setStatusesCount($accountInfo['status_count']);
		$account->setFriendsCount($accountInfo['friends_count']);
		$account->setAvatar($accountInfo['headurl']);
		$account->setTimeOfExpirationOfApiToken($oauthInfo['expires_in'] + time());
		$account->setTimeOfExpirationOfRefreshToken($oauthInfo['expires_in'] + mktime(date("H"), date("i"), date("s"), date("n")+1, date("j"), date("Y")));
	}


	/**
	 *
	 */

	public function connectDriver($params = null)
	{
		$rennClient = new \RennClient
		(
			pref('[Snsfg]/socialNetwork/renren/apikey'),
			pref('[Snsfg]/socialNetwork/renren/secretkey'),
			$params['privateApiToken']
		);

		return $rennClient;
	}


	/**
	 *
	 */

	public function postImage(&$account, $messageData)
	{
		$rennClient = $this->connectDriver
							(
									array
									(
										'privateApiToken' => $account->getPrivateApiToken()
									)
								);

		$postStatus = new CPostStatus();


		$myfile = array
		(
			'upload' => $messageData['pic']
		);
		$params = array
		(
			'caption' => $messageData['content'],
			'access_token' => $account->getPrivateApiToken()
		);

		$result = $renrenRestApi->rr_photo_post_fopen('photos.upload', $params, $myfile);

		if(is_uploaded_file($messageData['pic']['tmp_name']))
		{
			$picNewName = $account->getInternalId() . $account->getReference() . md5($messageData['pic']['tmp_name']) . $messageData['pic']['name'];
			$pathToUploadFile = PATH_TEMPORARY . $picNewName;
			copy( $messageData['pic']['tmp_name'], $pathToUploadFile );

			$postStatus->setPicture($picNewName);
		}


		$preg = '/http:\/\/t.cn\/[a-zA-Z0-9]*/';

		if(preg_match_all($preg, $result['caption'],$shortUrlRaws)) {
			$shortUrlStr = implode(',', $shortUrlRaws[0]);
			$postStatus->setShortUrl($shortUrlStr);
		}

		$postStatus->setAccountId($result['uid']);
		$postStatus->setContent($result['caption']);
		$postStatus->setInternalId($result['pid']);
		$postStatus->setRepostsCount(0);
		$postStatus->setCommentsCount(0);
		$postStatus->setCreatedAt(time());
		$postStatus->setSocialNetwork($account->getSocialNetwork());
		$postStatus->setType($messageData['type']);
		$postStatus->save();

		$dataToEF['statusId'] = $result['pid'];
		$dataToEF['content'] = $result['caption'];
		$dataToEF['socialNetwork'] = $account->getSocialNetwork();
		$dataToEF['efId'] = $account->getEfId();

		return $dataToEF;
	}


	/**
	 *
	 */

	public function postMessage(&$account, $messageData)
	{
		$rennClient = $this->connectDriver
							(
									array
									(
										'privateApiToken' => $account->getPrivateApiToken()
									)
								);

		$dataToEF = array();
		$postStatus = new CPostStatus();

		$params = array
		(
			'status' => $messageData['content'],
			'access_token' => $account->getPrivateApiToken()
		);
		
		$result = $renrenRestApi->rr_post_curl('status.set', $params);
		
		$newParams = array
		(
			'access_token' => $account->getPrivateApiToken()
		);

		$result = $renrenRestApi->rr_post_curl('status.get', $newParams);


		$preg = '/http:\/\/t.cn\/[a-zA-Z0-9]*/';

		if(preg_match_all($preg, $result['message'],$shortUrlRaws)) {
			$shortUrlStr = implode(',', $shortUrlRaws[0]);
			$postStatus->setShortUrl($shortUrlStr);
		}

		$postStatus->setAccountId($result['uid']);
		$postStatus->setContent($result['message']);
		$postStatus->setInternalId($result['status_id']);
		$postStatus->setRepostsCount(0);
		$postStatus->setCommentsCount(0);
		$postStatus->setSource($result['source_name']);
		$postStatus->setCreatedAt(strtotime($result['time']));
		$postStatus->setSocialNetwork($account->getSocialNetwork());
		$postStatus->setType($messageData['type']);
		$postStatus->save();

		$dataToEF['statusId'] = $result['status_id'];
		$dataToEF['content'] = $result['message'];
		$dataToEF['socialNetwork'] = $account->getSocialNetwork();
		$dataToEF['efId'] = $account->getEfId();

		return $dataToEF;

	}


	/**
	 *
	 */

	public function postStatus(&$account, $messageData)
	{
		

		switch ($messageData['type']) {
			case 'image':
				$result = $this->postImage($account, $messageData);
				break;

			case 'link':
				$result = $this->shareLink($account, $messageData);
				break;

			case 'status':
				$result = $this->postMessage($account, $messageData);
				break;
		}

		return $result;	
	}


	/**
	 *
	 */


	public function shareLink(&$account, $messageData)
	{

		$rennClient = $this->connectDriver
							(
									array
									(
										'privateApiToken' => $account->getPrivateApiToken()
									)
								);

		$dataToEF = array();
		$postStatus = new CPostStatus();


		$rennClient = $this->connectDriver
							(
									array
									(
										'privateApiToken' => $account->getPrivateApiToken()
									)
								);

		$params = array
		(
			'type' => 6,
			'url' => $messageData['link'],
			'comment' => $messageData['content'],
			'access_token' => $account->getPrivateApiToken()
		);
		
		$result = $renrenRestApi->rr_post_curl('share.share', $params);


		$preg = '/http:\/\/t.cn\/[a-zA-Z0-9]*/';

		if(preg_match_all($preg, $messageData['content'],$shortUrlRaws)) {
			$shortUrlStr = implode(',', $shortUrlRaws[0]);
			$postStatus->setShortUrl($shortUrlStr);
		}

		$postStatus->setAccountId($result['user_id']);
		$postStatus->setContent($messageData['content']);
		$postStatus->setInternalId($result['id']);
		$postStatus->setRepostsCount(0);
		$postStatus->setCommentsCount(0);
		$postStatus->setDiscription($result['summary']);
		$postStatus->setCreatedAt(time());
		$postStatus->setSocialNetwork($account->getSocialNetwork());
		$postStatus->setType($messageData['type']);
		$postStatus->save();

		$dataToEF['statusId'] = $result['id'];
		$dataToEF['content'] = $messageData['content'];
		$dataToEF['socialNetwork'] = $account->getSocialNetwork();
		$dataToEF['efId'] = $account->getEfId();

		return $dataToEF;
	}


	/**
	 *
	 */
	 	
	public function startConnection(&$account)
	{
		$rennClient = new \RennClient
		(
			pref('[Snsfg]/socialNetwork/renren/apikey'),
			pref('[Snsfg]/socialNetwork/renren/secretkey')
		);


		$callbackParameter = array
		(
			'accountId' => $account->getId(),
			'accountReference' => $account->getReference(),
			'urlOfRedirection' => pref('[Snsfg]/socialNetwork/renren/urlOfRedirection')
		);

		$state = uniqid ( 'renren_', true );

		v('SESSION::accountId', $account->getId());
		v('SESSION::accountReference', $account->getReference());


		$code_url = $rennClient->getAuthorizeURL
		(
			url('api/json/Account.completeConnection', $callbackParameter),
			'code',
			$state,
			null,
			true
		);

		return $code_url;
	}


	/**
	 *
	 */

	public function updateImage(&$account, $statusId)
	{
		$rennClient = $this->connectDriver
							(
									array
									(
										'privateApiToken' => $account->getPrivateApiToken()
									)
								);

		$dataToEF = array();
		$postStatus = new CPostStatus();

		$postStatus->load($statusId);

		$params = array
				(
					'uid' => $postStatus->getAccountId(),
					'pids' => $postStatus->getInternalId(),
					'access_token' => $account->getPrivateApiToken()
				);

		$result = $renrenRestApi->rr_post_curl('photos.get', $params);
		$result = array_pop($result);

		$postStatus->setCommentsCount($result['comment_count']);
		$postStatus->save();

		$dataToEF['commentCount'] = $result['comment_count'];

		return $dataToEF;
	}


	/**
	 *
	 */

	public function updateLink(&$account, $statusId)
	{
		$rennClient = $this->connectDriver
							(
									array
									(
										'privateApiToken' => $account->getPrivateApiToken()
									)
								);

		$postStatus = new CPostStatus();

		$postStatus->load($statusId);


		$params = array
				(
					'share_id' => $postStatus->getInternalId(),
					'user_id' => $postStatus->getAccountId(),
					'access_token' => $account->getPrivateApiToken()
				);

	}


	/**
	 *
	 */

	public function updateMessage(&$account, $statusId)
	{
		$rennClient = $this->connectDriver
							(
									array
									(
										'privateApiToken' => $account->getPrivateApiToken()
									)
								);

		$postStatus = new CPostStatus();

		$postStatus->load($statusId);


		$params = array
				(
					'status_id' => $postStatus->getInternalId(),
					'access_token' => $account->getPrivateApiToken()
				);

		$result = $renrenRestApi->rr_post_curl('status.get', $params);

		$postStatus->setRepostsCount($result['forward_count']);
		$postStatus->setCommentsCount($result['comment_count']);
		$postStatus->save();

		$dataToEF['repostCount'] = $result['forward_count'];
		$dataToEF['commentCount'] = $result['comment_count'];

		return $dataToEF;
	}


	/**
	 *
	 */

	public function updateStatus(&$account)
	{

		$dataToEF = array();
		$rawStatuses = $account->getStatuses();

		foreach($rawStatuses as $rawStatus)
		{
			switch ($rawStatus['type']) {
				case 'image':
					$data = $this->updateImage($account, $rawStatus['id']);
					break;
				case 'link':
					// $data = $this->updateLink($account, $rawStatus['id']);
					break;
				case 'status':
					$data = $this->updateMessage($account, $rawStatus['id']);
					break;
			}

			$dataToEF[$rawStatus['internalId']] = $data;
		}

		return $dataToEF;
	}

	public function disconnect(&$account)
	{
		
	}

}

?>
